﻿///
/// Copyright, 
/// This application , code and content is free to copy and modify 
/// This code is for demo purposed only 
/// User at own risk. no legal obligations from my end.
/// The purpose of this code is to explore the SharePoint Audit facilities.
/// George Gergues , george.gergues@gmail.com
/// Thank you.
///



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace TIS
{
	public partial class Main : Form
	{

		public BindingList<SPWeb> blWebs = new BindingList<SPWeb>();
		public BindingList<SPList> blLists = new BindingList<SPList>();
		public BindingList<SPListItem> blItems = new BindingList<SPListItem>();
        public DataTable tblAuditData = new DataTable();
        public TIS.SPAuditDemo.Utils u = new SPAuditDemo.Utils();

		public Main()
		{
			InitializeComponent();            
		}

		private void Form1_Load(object sender, EventArgs e)
		{
            MessageBox.Show("This application is for demo purposes only... !!!\nUse as such.\nEnjoy and Thank you !!!", "SharePoint Audit Demo Application.");
		}

		private void btnConnect_Click(object sender, EventArgs e)
		{
			bool ss = checkConnect(txtSiteUrl.Text.Trim());
			if (ss)
			{                
				txtSiteUrl.BackColor = Color.Green;
				txtSiteUrl.ForeColor = Color.Wheat;
				fillWebs(txtSiteUrl.Text.Trim());
			}
			else
			{             
				txtSiteUrl.BackColor = Color.Red;
				txtSiteUrl.ForeColor = Color.Wheat;
			}
		}

		private void fillWebs(string siteURL)
		{
			blWebs.Clear();
			try
			{
				using (SPSite site = new SPSite(siteURL))
				{
					foreach (SPWeb web in site.AllWebs)
					{
						blWebs.Add(web);
					}
				}
				cbxWebs.DataSource = blWebs;
				cbxWebs.DisplayMember = "Title";
			}
			catch (Exception ex)
			{
				txtDEBUG.Text = "Webs Level :"  +  ex.Message;                
			}
				
		}

		private bool checkConnect(string SiteURL)
		{
			bool result = false;
			try 
				{
				using (SPSite site = new SPSite(SiteURL))
						{
					// get the web in the impersonated context
					using (SPWeb web = site.RootWeb)
					{
						if (web != null)
							result = true;                    
					}
				 }
		
				}
				catch (Exception ex )
				{
					txtDEBUG.Text = ex.Message;
				}

			return result;
	
		}

		private void cbxWebs_SelectedIndexChanged(object sender, EventArgs e)
		{
			blLists.Clear();
			try
			{
                txtDEBUG.Clear();                
				foreach (SPList  list in ((SPWeb)cbxWebs.SelectedItem).Lists)
				{
					blLists.Add(list);                                        
				}
                cbxLists.DataBindings.Clear();
				cbxLists.DataSource = blLists;
				cbxLists.DisplayMember = "Title";
			}
			catch (Exception ex)
			{
				txtDEBUG.Text = "List Level : " + ex.Message;                   
			}
			
		}

		private void cbxLists_SelectedIndexChanged(object sender, EventArgs e)
		{
			blItems.Clear();
			try
			{
				foreach (SPListItem item in ((SPList)cbxLists.SelectedItem).Items)
				{
					blItems.Add(item);
				}
                displayItemClear();
                cbxItems.DataBindings.Clear();
				cbxItems.DataSource = blItems;
				cbxItems.DisplayMember = "Title";                
			}
			catch (Exception ex)
			{
				txtDEBUG.Text = ex.Message;
			}
		}

        private void cbxItems_SelectedIndexChanged(object sender, EventArgs e)
        {            
            try
            {
                txtDEBUG.Clear();
                displayItemClear();
                cbxItems.DataBindings.Clear();
                cbxItems.DataSource = blItems;
                cbxItems.DisplayMember = "Title";                 
                displayItem((SPListItem)cbxItems.SelectedItem);
            }
            catch (Exception ex)
            {
                txtDEBUG.Text = "Item level: " + ex.Message;
            }
            
        }

        private void displayItemClear()
        {
            txtItemName.Text = string.Empty;
            txtItemTitle.Text = string.Empty;
            txtItemVersions.Text = string.Empty;
        }

        private void displayItem(SPListItem spi)
        {
            txtItemName.Text = spi.Name;
            txtItemTitle.Text = spi.Title;
            txtItemVersions.Text = spi.Versions.Count.ToString();
            
        }


        /// <summary>
        /// Audit the site collection 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnACollection_Click(object sender, EventArgs e)
        {           
            tblAuditData.Clear();            
            tblAuditData = u.getSiteCustomAuditTable(new SPSite(txtSiteUrl.Text.Trim()), false);
            dgvAuditData.AutoGenerateColumns = true;
            dgvAuditData.DataSource = tblAuditData;
        }

        private void btnAList_Click(object sender, EventArgs e)
        {
            tblAuditData.Clear();
            tblAuditData = u.getListCustomAuditFilteredTable(new SPSite(txtSiteUrl.Text.Trim()), (SPList)cbxLists.SelectedItem);
            dgvAuditData.AutoGenerateColumns = true;
            dgvAuditData.DataSource = tblAuditData;
        }

        private void btnAItem_Click(object sender, EventArgs e)
        {
            tblAuditData.Clear();
            tblAuditData = u.getItemCustomAuditFilteredTable(new SPSite(txtSiteUrl.Text.Trim()),(SPListItem) cbxItems.SelectedItem);
            dgvAuditData.AutoGenerateColumns = true;
            dgvAuditData.DataSource = tblAuditData;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                dlgSaveFile.Filter = "Excel File|*.xls|Html File|*.html";
                dlgSaveFile.FilterIndex = 1;
                dlgSaveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                dlgSaveFile.FileName = "MyListData-" + DateTime.Now.ToFileTime().ToString();
                DialogResult dlgResult = dlgSaveFile.ShowDialog();

                if (dlgResult == System.Windows.Forms.DialogResult.OK)
                {

                    //
                    ExcelConvertor converter = new ExcelConvertor();

                    string file =  converter.Convert(tblAuditData, this.dlgSaveFile.FileName);
                    
                }
            }

            catch (Exception ex)
            {
                dodgeThis(ex);
            }
        }

        private void dodgeThis(Exception ex)
        {
            txtDEBUG.Text+=  "Error Saving file : " + ex.Message + " __Error Details " + ex.Data;
        }
	}
}
